/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.tms.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.infor.entity.Goods;
import com.jeeplus.modules.infor.service.GoodsService;
import com.jeeplus.modules.tms.entity.SignDetil;
import com.jeeplus.modules.tms.entity.TmsMaterialsInformation;
import com.jeeplus.modules.tms.entity.TmsWaybill;
import com.jeeplus.modules.tms.service.SignDetilService;
import com.jeeplus.modules.tms.service.TmsWaybillService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.tms.entity.Receipt;
import com.jeeplus.modules.tms.service.ReceiptService;

/**
 * 回单签收Controller
 * @author 李超辉
 * @version 2017-12-06
 */
@Controller
@RequestMapping(value = "${adminPath}/tms/receipt")
public class ReceiptController extends BaseController {

	@Autowired
	private ReceiptService receiptService;
	@Autowired
	private TmsWaybillService waybillService;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private SignDetilService signDetilService;
	
	@ModelAttribute
	public Receipt get(@RequestParam(required=false) String id) {
		Receipt entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = receiptService.get(id);
		}
		if (entity == null){
			entity = new Receipt();
		}
		return entity;
	}
	
	/**
	 * 回单签收列表页面
	 */
	@RequiresPermissions("tms:receipt:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/tms/receiptList";
	}
	
		/**
	 * 回单签收列表数据
	 */
	@ResponseBody
	@RequiresPermissions("tms:receipt:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Receipt receipt, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Receipt> page = receiptService.findPage(new Page<Receipt>(request, response), receipt); 
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑回单签收表单页面
	 */
	@RequiresPermissions(value={"tms:receipt:view","tms:receipt:add","tms:receipt:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Receipt receipt,String i, Model model) {
		TmsWaybill bill=waybillService.get(i);
		model.addAttribute("tmsWaybill", bill);
		Receipt re=receiptService.findUniqueByProperty("bill",i);
		if(re!=null){model.addAttribute("receipt", re);}else{
			receipt.setBill(i);
 			receipt.setClienteleEntruckingNumber(bill.getZjs()+"");
			receipt.setCompanyEntruckingNumber(bill.getZjs()+"");
			receipt.setShipperEntruckingNumber(bill.getZjs()+"");
			model.addAttribute("receipt", receipt);
		}


		return "modules/tms/receiptForm";
	}
	/**
	 * 查看，增加，编辑回单签收表单页面(快捷流程)
	 */
	@RequiresPermissions(value={"tms:receipt:view","tms:receipt:add","tms:receipt:edit"},logical=Logical.OR)
	@RequestMapping(value = "form1")
	public String form1(Receipt receipt,String i, Model model) {
		TmsWaybill bill=waybillService.get(i);
		model.addAttribute("tmsWaybill", bill);
		Receipt re=receiptService.findUniqueByProperty("bill",i);
		if(re!=null){model.addAttribute("receipt", re);}else{
			receipt.setBill(i);

			model.addAttribute("receipt", receipt);
		}


		return "modules/tms/2/receiptForm";
	}

	/**
	 * 保存回单签收
	 */
	@ResponseBody
	@RequiresPermissions(value={"tms:receipt:add","tms:receipt:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Receipt receipt, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, receipt)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		TmsWaybill t=waybillService.get(receipt.getBill());
		SignDetil s=null;
		if(receipt.getIsNewRecord()){
			s=new SignDetil();
           s.setZydh(t.getShipmentNumbers());
           s.setThdh(t.getTh());
           s.setThd(t.getContractDistance());
           s.setKhmc(t.getUnitName());
           s.setWeight(t.getWeight());
           s.setDhd(t.getArrive());
           s.setDate(t.getDate());
           s.setRemarks(t.getRemarks());
           s.setPro(t.getProjectName());
		}else{
			s=signDetilService.findUniqueByProperty("hd",receipt.getId());
		}
		receiptService.save(receipt);//新建或者编辑保存
		if(s!=null){
			if(receipt.getClienteleSignTime()!=null){
				s.setKhqszt("已签收");
			}else{
				s.setKhqszt("未签收");
			}
			if(receipt.getCompanySignTime()!=null){
				s.setGsqszt("已签收");
			}else{
				s.setGsqszt("未签收");
			}
			if(receipt.getShipperSignTime()!=null){
				s.setHzqszt("已签收");
			}else{
				s.setHzqszt("未签收");
			}
		s.setKhqsrq(receipt.getClienteleSignTime());
		s.setGsqsrq(receipt.getCompanySignTime());
		s.setHzqsrq(receipt.getShipperSignTime());
		s.setHd(receipt.getId());
        signDetilService.save(s);}

		if(receipt.getCompanyCollectName()!=null&receipt.getCompanyCollectName().length()>0){
			t.setStatus("已回单");

		}
		if(receipt.getClienteleCollectState().equals("异常")||receipt.getCompanyCollectState().equals("异常")||receipt.getShipperCollectState().equals("异常")){
			t.setZt("异常");
		}else{
			t.setZt("正常");
		}
		t.setBillStatus("已签收");
		t.setQsr(receipt.getClienteleCollectName());
		t.setQszt(receipt.getClienteleCollectState());
		t.setQsjs(receipt.getClienteleSignNumber());
		waybillService.save(t);
		j.setSuccess(true);
		j.setMsg("保存回单签收成功");
		return j;
	}
	
	/**
	 * 删除回单签收
	 */
	@ResponseBody
	@RequiresPermissions("tms:receipt:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Receipt receipt, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		receiptService.delete(receipt);
		j.setMsg("删除回单签收成功");
		return j;
	}
	
	/**
	 * 批量删除回单签收
	 */
	@ResponseBody
	@RequiresPermissions("tms:receipt:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			receiptService.delete(receiptService.get(id));
		}
		j.setMsg("删除回单签收成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("tms:receipt:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(Receipt receipt, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "回单签收"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Receipt> page = receiptService.findPage(new Page<Receipt>(request, response, -1), receipt);
    		new ExportExcel("回单签收", Receipt.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出回单签收记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("tms:receipt:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Receipt> list = ei.getDataList(Receipt.class);
			for (Receipt receipt : list){
				try{
					receiptService.save(receipt);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条回单签收记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条回单签收记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入回单签收失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/tms/receipt/?repage";
    }
	
	/**
	 * 下载导入回单签收数据模板
	 */
	@RequiresPermissions("tms:receipt:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "回单签收数据导入模板.xlsx";
    		List<Receipt> list = Lists.newArrayList(); 
    		new ExportExcel("回单签收数据", Receipt.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/tms/receipt/?repage";
    }

}